package com.anlu.base.common.security.service;

import com.anlu.base.admin.api.dto.UserDTO;
import com.anlu.base.admin.api.dto.UserInfo;
import com.anlu.base.admin.api.feign.RemoteUserService;
import com.anlu.base.common.core.constant.CacheConstants;
import com.anlu.base.common.core.util.R;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Primary;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
@Slf4j
@Primary
@RequiredArgsConstructor
public class PigUserDetailsServiceImpl implements PigUserDetailsService{
    private final RemoteUserService remoteUserService;

    private final CacheManager cacheManager;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Cache cache = cacheManager.getCache(CacheConstants.USER_DETAILS);
        if(cache != null &&  cache.get(username)!=null){
            return (UserDetails) cache.get(username).get();
        }

        UserDTO userDTO = new UserDTO();
        userDTO.setUsername(username);
        R<UserInfo> result = remoteUserService.info(userDTO);
        UserDetails userDetails = getUserDetails(result);
        if(cache != null){
            cache.put(username,userDetails);
        }
        return userDetails;
    }

    @Override
    public int getOrder() {
        return Integer.MIN_VALUE;
    }
}
